#!/usr/bin/python3

from telnetlib import Telnet
import re
import time

def copyips(username, password, rackno, verno):

    ipssig = re.compile(r'^service interface.*')

	if rackno == 'BJRack01':
		rackip = '172.17.100.111'
	elif rackno == 'BJRack02':
		rackip = '172.17.100.112'
	elif rackno == 'BJRack03':
		rackip = '172.17.100.113'

	portno = 2017

	tn = Telnet(rackip, portno)

	tn.write(b'\r\n')
	tn.read_very_eager()
	time.sleep(1)
	tn.write(b'\r\n')
	tn.read_very_eager()
	time.sleep(1)
	tn.write(b'\r\n')
	tn.read_very_eager()
	time.sleep(1)
	tn.write(b'\n')
	tn.write(b'\n')
	time.sleep(1)
	tn.write(b'cisco\n')
	time.sleep(2)
	tn.write(b'123cisco123\n')
	tn.write(b'\n\n\n')
	time.sleep(1)
	tn.write(b'end\n\n')
	time.sleep(1)
	tn.write(b'end\n\n')
	time.sleep(1)
	tn.write(b'terminal length 0\n\n')
	time.sleep(1)
	tn.write(b'terminal length 0\n\n')
	time.sleep(1)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	tn.write(b'show configuration\n\n')
	rackreplyipst = tn.expect([],timeout=60)[2].decode().strip()
#	print(rackreplyipst)
	configfiletmp = '/python/cgi-bin/tmpconfig/' + verno + '/' + 'IPST' + '.txt'
	configtmp = open(configfiletmp, 'w')
	configtmp.write(rackreplyipst)
	configtmp.close
	time.sleep(1)
	configtmp = open(configfiletmp, 'r')
#	print(configtmpr)
#	configtmptest = open(configfiletmp, 'r').read()
#	print(configtmptest)
	rackreplylines = configtmp.readlines()

#	print(rackreplylines)
	rackreplylinesnew = []
	for line in rackreplylines:
		if line == '\n':
			pass
		else:
			rackreplylinesnew.append(line)

	location = 1
	i = 1
	for line in rackreplylinesnew:
		i = i + 1
		if ipssig.match(line.strip()):
			location = i - 2
			print(location)

	ipsconfiglst = rackreplylinesnew[location:]
	ipsconfig = ''.join(str(e) for e in ipsconfiglst)
	configfile = '/python/cgi-bin/tmpconfig/' + verno + '/' + 'IPS' + '.txt'
	config = open(configfile, 'w')
	config.write(ipsconfig)
	config.close()
	tn.close()


if __name__ == "__main__":
	copyips('labtest', 'Cisc0123', 'BJRack03', 'v12')